package com.hjx.controller;

import com.hjx.logging.LogAnnotation;
import com.hjx.response.AjaxResponse;
import com.hjx.response.ResponseType;
import com.hjx.security.JwtAuthService;
import com.hjx.util.JwtAuthTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/10 - 9:02
 */
@RestController
public class JwtAuthController {
    @Resource
    JwtAuthService jwtAuthService;
    @Resource
    RedisTemplate<String,String> redisTemplate;

    @PostMapping("/testApi")
    public AjaxResponse test() {
        return new AjaxResponse(ResponseType.OPERATION_SUCCESS, null);
    }

    @LogAnnotation
    @PostMapping(value = "/authentication")
    public AjaxResponse login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return new AjaxResponse(ResponseType.USERNAME_OR_PASSWORD_IS_NULL);
        }
        try {
            //成功则将JWT认证结果返回
            String token = jwtAuthService.login(username, password);
            //将登录后获得的最新的token存入redis中
            redisTemplate.opsForValue().set(username,token);
            return new AjaxResponse(ResponseType.LOGIN_SUCCESS,token);
        } catch (AuthenticationException e) {
            //失败则返回错误信息
            return new AjaxResponse(ResponseType.USERNAME_OR_PASSWORD_ERROR);
        }
    }
    @LogAnnotation
    @RequestMapping("/userLogout")
    public AjaxResponse userLogout() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        final Boolean result = redisTemplate.delete(username);
        if (result!=null&&result) {
            return new AjaxResponse(0,"登出成功",null);
        }
        return new AjaxResponse(1, "登出失败", null);
    }

    @LogAnnotation
    @RequestMapping("/refreshToken")
    public AjaxResponse refresh(@RequestHeader("${jwt.header}") String token) {
        String refreshToken = jwtAuthService.refreshToken(token);
        if (refreshToken != null) {
            return new AjaxResponse(0, "刷新token成功", refreshToken);
        }
        return new AjaxResponse(1, "token已过期", null);
    }
}
